import React, { useState, useCallback, useMemo } from 'react';
import { Modal } from 'antd';
import { createParamsUrl } from './util';

const useFileFetch = () => {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(true);
  const [fileLink, setFileLink] = useState('');
  const fetchFile = async (fileURL) => {
    setVisible(true);
    const data = await fetch(fileURL).then((res) => res.ok && res.blob());
    // eslint-disable-next-line no-unused-expressions
    data && setFileLink(window.URL.createObjectURL(data));
    setLoading(false);
  };
  const hiddenFile = () => {
    setVisible(false);
  };
  return { loading, visible, fetchFile, hiddenFile, fileLink };
};

function FullPreFile(props) {
  const { visible, loading, hiddenFile, viewName, fileLink } = props;

  const modalProps = useMemo(() => {
    const name = viewName || '';
    const width = document.documentElement.clientWidth;
    return {
      width,
      visible,
      loading,
      footer: null,
      onOk: hiddenFile,
      onCancel: hiddenFile,
      title: `预览- ${name}`,
      wrapClassName: 'pre-view',
    };
  }, [loading, visible, hiddenFile, viewName]);

  const onLoad = useCallback((e) => {
    try {
      const content = e.currentTarget.contentWindow;
      const bodyIframe = content.document.body;
      bodyIframe.style.display = 'flex';
      bodyIframe.style.alignItems = 'center';
      bodyIframe.style.justifyContent = 'center';
    } catch (error) {
      console.log('非chrome浏览器 可能 ifrom document 获取方式API不同', error);
    }
  }, []);

  const iframeProps = useMemo(() => {
    const height = document.documentElement.clientHeight;
    return {
      src: fileLink,
      onLoad,
      align: 'center',
      frameBorder: '0',
      style: {
        width: '100%',
        display: 'flex',
        height,
      },
    };
  }, [onLoad, fileLink]);

  return (
    <Modal {...modalProps} destroyOnClose>
      <iframe title="name" {...iframeProps} />
    </Modal>
  );
}

function PreFileView(props) {
  const { viewUrl, viewId, viewCode, viewName } = props;
  const { loading, visible, fetchFile, hiddenFile, fileLink } = useFileFetch();

  const fileURL = useMemo(() => {
    if (viewUrl) return viewUrl;
    return createParamsUrl({ fileId: viewId, fileCode: viewCode }, 'download');
  }, [viewUrl, viewId, viewCode]);

  return (
    <React.Fragment>
      <a onClick={fetchFile.bind(null, fileURL)} style={{ marginRight: 8 }}>
        预览
      </a>

      <FullPreFile
        visible={visible}
        loading={loading}
        viewName={viewName}
        fileLink={fileLink}
        hiddenFile={hiddenFile}
      />
    </React.Fragment>
  );
}

export default PreFileView;
